<!doctype html>
<html lang="zh" ng-app="app">
<head>
  <meta charset="utf-8">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="viewport" content="initial-scale=1.1,user-scalable=no">
  <title>救援</title>  
  
  <link rel="stylesheet" href="/static/weixin/css/app.css">
  
  <script src="/static/weixin/js/config.js"></script>

  <script src="/static/weixin/js/zarpemain.js"></script>
  

  <script>
    ons.ready(function() {
    });
  </script>
  <style>
    .row{
      padding: 10px;
    }
    .col{
      padding: 0 10px 0 10px;
    }

    .col p, i{
      margin: 10px;
    }

    .col .icon, i{
      text-align: center;
      color:#50bba5;
    }
  </style>
</head>

<body ng-controller="SaveMeController as Ctrl" class="ng-cloak">    
  <ons-page>

    <div id="mapContainer" style="height:300px; width:100%; background-color:#C4C4C4">

    </div>
    <section style="padding:8px">
      <ons-button modifier="large" ng-attr-disabled="{{!hasLocation}}" ng-click="confirmSubmit()">一键救援</ons-button>
    </section>
    <ons-row>
      <h3>救援电话</h3>
    </ons-row>
    <ons-row>
      <ons-col width="40%">
        <p>24小时救援</p>
      </ons-col>
      <ons-col width="45%">
        <p>{{dealer.phone}}</p>
      </ons-col>
      <ons-col class="icon">
        <a ng-href="tel:{{dealer.phone}}"><i class="fa fa-phone fa-lg"></i></a>
      </ons-col>
    </ons-row>
    <ons-row>
      <ons-col width="40%">
        <p>交警</p>
      </ons-col>
      <ons-col width="45%">
        <p>122</p>
      </ons-col>
      <ons-col class="icon">
        <a href="tel:122"><i class="fa fa-phone fa-lg"></i></a>
      </ons-col>
    </ons-row>
  </ons-page>
  <ons-template id="dialog.html">
    <ons-dialog style="height:150px" animation="default" cancelable>
  </ons-dialog> 
  </ons-template>
  <script src="http://webapi.amap.com/maps?v=1.3&key=dcf70917a82346c63caccb6deb1bc953" type="text/javascript"></script>
  <script>

    var lngLat,
        mapLoaded = false,
        map,
        geoLocation,
        marker;


    (function(){
      'use strict';
      var module = angular.module('app', ['onsen','ngCookies']);
      module.constant("baseUrl", zarpe_config.baseUrl);
      module.controller('SaveMeController', ['$scope','$http', 'baseUrl', '$window','Customer', 'Dealer', '$cookieStore',function($scope, $http, baseUrl, $window, customerService, dealerService, $cookieStore ) {

        if( $cookieStore.get('rescuesent')){
          $cookieStore.remove('rescuesent');
        }

        $scope.hasLocation = false;

        // getLocation
        function getLocation(){

          var onComplete = function(result){
            $scope.$apply( function(){
              $scope.hasLocation = true;
              var position = result.position;
              $scope.latitude = position.getLat();
              $scope.longitude = position.getLng();
            });
          };

          var onError = function(){
            ons.notification.alert({
              title:'错误',
              message:'无法完成定位，请拨打电话申请救援',
              callback: function(){
                // do nothing.
              }
            });
            $scope.$apply( function(){
              $scope.hasLocation = false;
            })
          };
          
          map = new AMap.Map('mapContainer', {
            resizeEnable: true,
            rotateEnable: true,
            dragEnable: true,
            zoomEnable: true,
          });
          map.plugin('AMap.Geolocation', function(){
            geoLocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                maximumAge: 0,           //定位结果缓存0毫秒，默认：0
                convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                showButton: true,        //显示定位按钮，默认：true
                buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
                panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            });
            map.addControl(geoLocation);
            AMap.event.addListener(geoLocation, 'complete', onComplete);//返回定位信息
            AMap.event.addListener(geoLocation, 'error', onError);      //返回定位出错信息
            geoLocation.getCurrentPosition();
          });
  
        }; // end of getLocation()

        dealerService.then( function(result){
          if( result.status >= 200 && result.status <= 299 ){
            $scope.dealer = result.data;
          }else{
            ons.notification.alert({
              title:'错误',
              message:'获取数据错误，请稍候再试',
            });
          }
          
        });

        customerService.then( function( result ){
          if( result.status >= 200 && result.status <= 299 ){
            $scope.phone = result.data.phone;
            getLocation();
          }else{
            ons.notification.alert({
              title:'错误',
              message:'获取数据错误，无法使用一键救援，请直接拨打24小时救援电话，或者交警电话122',
            });
          }
        });

        
        $scope.confirmSubmit = function(){
          var rescueObj = {
            latitude: $scope.latitude,
            longitude: $scope.longitude,
            phone: $scope.phone
          };

          if( !rescueObj.latitude || !rescueObj.longitude || !rescueObj.phone || !rescueObj.phone.length ){
            ons.notification.alert({
              title:'错误',
              message:'错误。请稍候再试',
            });
          }else{
            ons.notification.confirm({
              title:null,
              buttonLabels: ['取消', '确认'],
              message:'确定发送救援申请?',
              callback: function( idx ){
                switch( idx ){
                  case 0:
                    // DO nothing.
                    break;
                  case 1:
                    var isSent = $cookieStore.get('rescuesent');
                    if( isSent ){
                      ons.notification.alert({
                        title:'注意',
                        message:'您已经发送过了救援，正在实施中，请耐心等候。',

                      });
                      return;
                    }
                    $http.post(baseUrl+'rescue/', rescueObj).success( function(data){
                      ons.notification.alert({
                        title:'',
                        message:'尊敬的客户，我们已经收到您的救援请求。我们将马上安排救援人员和您联系，请您耐心等候。',
                      });
                      $cookieStore.put('rescuesent',true);
                    }).error( function(data){
                      ons.notification.alert({
                        title:'错误',
                        message:'请稍后再试，或直接拨打救援电话。',
                      })
                    });
                    break;
                } // end of switch statement
              } // end of confirm.callback
            }); // end of confirm.
          } // end of else
          
        }
      }]);

      module.factory('Customer', ['$http','baseUrl', '$cookies', 'Sharing', function($http, baseUrl, $cookies, shares ){
        function getURLParameter(name) {
          return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
        }

        shares.set('wechat_open_id', getURLParameter('wechat_open_id'));
        shares.set('dealer', getURLParameter('dealer'));

        var customerId = $cookies.customer;
         // var customerId = 1; 
        if( !customerId ){
          window.location = "bindme.html?dealer="+shares.get('dealer')+"&wechat_open_id="+shares.get('wechat_open_id');
        }else{
          return $http.get(baseUrl+"customers/"+customerId+"/");
        }
      }]);

      module.factory('Dealer', ['$http','baseUrl', '$cookies',  function($http, baseUrl, $cookies){
        var dealerId = $cookies.dealer;
/*         var dealerId = 1; */
        if( !dealerId ){
          ons.notification.alert({
            title:'错误',
            message:'获取数据失败。请稍候再试。',
            callback: function(){
              // do nothing.
            }
          });
          return;
        }else{
          return $http.get(baseUrl+"dealers/"+dealerId+"/");
        }
      }]);

      // Sharing
      module.factory('Sharing', function(){
        var store = {};

        return {
            set: function( key, value ){
                store[key] = value;
            },

            get: function( key ){
                return store[key];
            }
        }
    });

    })();
  </script>
</body>  
</html>
